<template>
  <el-dialog
    :title="`${drawerProps.title}任务`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="1400px"
    :destroy-on-close="true"
  >
    <el-form
      ref="ruleFormRef"
      style="height: 70vh; overflow: hidden auto"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-row>
        <el-col :span="16">
          <group-title title="基本信息"></group-title>
          <el-row>
            <form-item title="任务名称" prop="name" :title-span="3" :item-span="21">
              <el-input v-model="drawerProps.row!.name" clearable></el-input>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="任务编号" prop="task_no" :title-span="3" :item-span="5">
              <el-input v-model="drawerProps.row!.task_no" clearable></el-input>
            </form-item>
            <form-item title="任务类别" prop="category" :title-span="3" :item-span="5">
              <cascader-select
                data-key="TASK_CATEGORY"
                :request-api="() => apiService.findTree('param_exts', { csName: 'TASK_CATEGORY' }, { sort: { sort: 1 } })"
                :config="{ label: 'name', value: '_id' }"
                v-model:item-value="drawerProps.row!.category"
              ></cascader-select>
            </form-item>
            <form-item title="任务来源" prop="task_source" :title-span="3" :item-span="5">
              <common-select
                data-key="TASK_SOURCE"
                placeholder="请选择任务重要性"
                :request-api="() => apiService.findClassify('TASK_SOURCE')"
                v-model="drawerProps.row!.task_source"
              ></common-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="所属项目" :title-span="3" :item-span="5">
              <item-select placeholder="请选择项目" v-model="drawerProps.row!.item_id"></item-select>
            </form-item>
            <form-item title="重要性" :title-span="3" :item-span="5">
              <common-select
                data-key="TASK_IMPORTANT"
                placeholder="请选择任务重要性"
                :request-api="() => apiService.findClassify('TASK_IMPORTANT')"
                v-model="drawerProps.row!.important"
              ></common-select>
            </form-item>
            <form-item title="优先级" :title-span="3" :item-span="5">
              <common-select
                data-key="TASK_PRIORITY"
                placeholder="请选择任务优先级"
                :request-api="() => apiService.findClassify('TASK_PRIORITY')"
                v-model="drawerProps.row!.priority"
              ></common-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="任务内容" prop="summary" :title-span="3" :item-span="21">
              <WangEditor height="300px" v-model:value="drawerProps.row.summary" :editor-config="editConfig" mode="simple" />
              <!-- <el-input type="textarea" :rows="8" v-model="drawerProps.row!.summary" clearable></el-input> -->
            </form-item>
          </el-row>
          <!-- <el-row> -->
          <!-- <form-item title="执行计划" :title-span="3" :item-span="21"> -->
          <!-- <WangEditor height="300px" v-model:value="drawerProps.row.summary" :editor-config="editConfig" mode="simple" /> -->
          <!-- <el-input type="textarea" :rows="5" v-model="drawerProps.row!.work_plan" clearable></el-input>
            </form-item> -->
          <!-- </el-row> -->
          <group-title title="执行情况" v-if="drawerProps.row!._id"></group-title>
          <business-comment
            v-if="drawerProps.row!._id"
            placeholder="请输入执行情况"
            :business-id="drawerProps.row!._id"
            :business-type="BusinessType.TASK"
          ></business-comment>
        </el-col>
        <el-col :offset="1" :span="7">
          <group-title title="执行信息"></group-title>
          <el-row>
            <form-item title="发布人" prop="publish_user" :title-span="8" :item-span="14">
              <user-select placeholder="请选择用户" v-model="drawerProps.row!.publish_user"></user-select>
            </form-item>
            <form-item title="接收时间" prop="create_at" :title-span="8" :item-span="14">
              <el-date-picker style="width: 100%" v-model="drawerProps.row!.create_at" type="date" placeholder="选择接收时间" />
            </form-item>
            <form-item title="要求完成时间" :title-span="8" :item-span="14">
              <el-date-picker
                style="width: 100%"
                v-model="drawerProps.row!.end_date"
                type="date"
                placeholder="选择要求完成时间"
              />
            </form-item>
            <form-item title="分管副总" prop="manage_user" :title-span="8" :item-span="14">
              <user-select :param="{ post: 2 }" placeholder="请选择用户" v-model="drawerProps.row!.manage_user"></user-select>
            </form-item>
            <form-item title="督办人" :title-span="8" :item-span="14">
              <user-select :param="{ post: 14 }" placeholder="请选择用户" v-model="drawerProps.row!.supervisor"></user-select>
            </form-item>
            <form-item title="任务负责人" prop="user_id" :title-span="8" :item-span="14">
              <user-select placeholder="请选择用户" v-model="drawerProps.row!.user_id"></user-select>
            </form-item>
            <form-item title="执行状态" prop="state" :title-span="8" :item-span="14">
              <common-select
                data-key="FLOW_STATE"
                placeholder="请选择状态"
                :request-api="() => apiService.findClassify('FLOW_STATE')"
                v-model="drawerProps.row!.state"
              ></common-select>
            </form-item>
          </el-row>
          <group-title title="附件"></group-title>
          <el-row>
            <el-col :span="22">
              <UploadFiles v-model:file-list="drawerProps.row.files" :drag="false" border-radius="50%"></UploadFiles>
            </el-col>
          </el-row>
          <!-- <group-title v-if="drawerProps.row!._id" title="操作记录"></group-title>
          <el-row>
            <el-col :span="22">
              <business-action v-if="drawerProps.row!._id" :business-id="drawerProps.row!._id"></business-action>
            </el-col>
          </el-row> -->
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { KeyTask } from "@/api/types/base";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import userSelect from "@/components/SelectFilter/user-select.vue";
import itemSelect from "@/components/SelectFilter/item-select.vue";
import apiService from "@/api/services/apiService";
import groupTitle from "@/components/application/form/group-title.vue";
import formItem from "@/components/application/form/form-item.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import UploadFiles from "@/components/Upload/Files.vue";
import { useUserStore } from "@/stores/modules/user";
import CascaderSelect from "@/components/SelectFilter/cascader-select.vue";
// import businessAction from "@/components/application/action/business-action.vue";
import businessComment from "@/components/application/comment/business-comment.vue";
import { BusinessType, BusinessOptType, MessageType } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";
import { IEditorConfig } from "@wangeditor/editor";
import { useMessage } from "@/hooks/useMessage";
import { generateUUID } from "@/utils";

const { addUserAction } = useUserAction(BusinessType.TASK);
const { sendSysMessage } = useMessage(BusinessType.TASK);
const userStore = useUserStore();

const rules = reactive({
  name: [{ required: true, message: "请输入任务名称" }],
  task_no: [{ required: true, message: "请输入任务编号" }],
  category: [{ required: true, message: "请选择任务类别" }],
  task_source: [{ required: true, message: "请选择任务来源" }],
  summary: [{ required: true, message: "请输入任务内容" }],
  create_at: [{ required: true, message: "请选择接收时间" }],
  manage_user: [{ required: true, message: "请选择分管副总" }],
  user_id: [{ required: true, message: "请选择任务负责人" }],
  state: [{ required: true, message: "请选择任务状态" }]
});

const editConfig: Partial<IEditorConfig> = {
  placeholder: "请输入任务详情……",
  MENU_CONF: {}
};

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<KeyTask>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的任务
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title.indexOf("新增") != -1) {
    const { data } = await apiService.nextValue("task_no");
    drawerProps.value.row.task_no = "T" + data;
    console.log(drawerProps.value.row);
  }
};

const onCancel = async () => {
  if (!drawerProps.value.row._id) {
    await apiService.reNextValue("task_no");
  }
  drawerVisible.value = false;
};

// 提交数据（新增/编辑）任务
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (drawerProps.value.title.indexOf("新增") != -1) {
        drawerProps.value.row.task_id = generateUUID();
        drawerProps.value.row.create_user = userStore.userInfo._id;
      } else {
        drawerProps.value.row.updated_at = new Date();
      }

      console.log(drawerProps.value.row);
      const { data } = await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      console.log(data);
      ElMessage.success({ message: `${drawerProps.value.title}任务成功！` });
      if (drawerProps.value.title.indexOf("新增") != -1) {
        addUserAction(data._id, BusinessOptType.ADD, data.name);
        sendSysMessage(data._id, `你有一个新的任务【${data.name}】，请及时处理`, data.summary, MessageType.TODO, [data.user_id]);
      } else {
        addUserAction(drawerProps.value.row._id, BusinessOptType.UPDATE, drawerProps.value.row.name);
      }
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
